import './home.css'
import table from '@/assets/home/table.png'
import source from '@/assets/home/source.png'
import order from '@/assets/home/order.png'
import plan from '@/assets/home/plan.png'
import deliver from '@/assets/home/deliver.png'
import data from '@/assets/home/data.png'
import project from '@/assets/home/project.png'
import step1 from '@/assets/home/step1.png'
import step2 from '@/assets/home/step2.png'
import step3 from '@/assets/home/step3.png'
import step4 from '@/assets/home/step4.png'
import shortLine from '@/assets/home/shortLine.png'
import longLine from '@/assets/home/longLine.png'
import PieChart from '@/views/components/PieChart.tsx'
import TrendNum from '@/views/components/TrendNum.tsx'
import CountUp from 'react-countup'
import LineChart from '@/views/components/LineChart.tsx'
import { useEffect, useState } from 'react'
import {
  getBottomAssets,
  getBottomDemand,
  getBottomPlan,
  getBottomProduction,
  getCardDemand,
  getCardPlan,
  getCardPlanTrend,
  getCardProduction,
  getCardProductionTrend,
  getCardSource,
  getCardTable,
  getCardTag,
  getCardTopRank,
  getHeadDemand,
  getHeadPlan,
  getHeadProject,
  getHeadSourceTable
} from '@/api/home.ts'
import dayjs from 'dayjs'
import { useNavigate } from 'react-router-dom'

const countItems = [
  {
    label: '数据表',
    img: table,
    unit: '张',
    percent: false
  },
  {
    label: '数据源',
    img: source,
    unit: '个',
    percent: false
  },
  {
    label: '规划订单总量',
    img: order,
    unit: '个',
    percent: false
  },
  {
    label: '规划完成度',
    img: plan,
    unit: '',
    percent: true
  },
  {
    label: '交付需求',
    img: deliver,
    unit: '次',
    percent: false
  },
  {
    label: '交付数据总量',
    img: data,
    unit: '条',
    percent: false
  },
  {
    label: '服务项目数',
    img: project,
    unit: '个',
    percent: false
  }
] as const
type HeadItems = (typeof countItems)[number]['label']

const HomeHead = () => {
  const [headNum, setHeadNum] = useState<
    Record<
      HeadItems,
      {
        value: number
        monthValue: number
        weekValue: number
      }
    >
  >({
    数据表: {
      value: 0,
      monthValue: 0,
      weekValue: 0
    },
    数据源: {
      value: 0,
      monthValue: 0,
      weekValue: 0
    },
    规划订单总量: {
      value: 0,
      monthValue: 0,
      weekValue: 0
    },
    规划完成度: {
      value: 0,
      monthValue: 0,
      weekValue: 0
    },
    交付需求: {
      value: 0,
      monthValue: 0,
      weekValue: 0
    },
    交付数据总量: {
      value: 0,
      monthValue: 0,
      weekValue: 0
    },
    服务项目数: {
      value: 0,
      monthValue: 0,
      weekValue: 0
    }
  })
  useEffect(() => {
    getHeadSourceTable().then((res) => {
      setHeadNum((value) => ({
        ...value,
        数据表: {
          value: res.data_table.total,
          monthValue: res.data_table.month_week_growth.month,
          weekValue: res.data_table.month_week_growth.week
        },
        数据源: {
          value: res.data_source.total,
          monthValue: res.data_source.month_week_growth.month,
          weekValue: res.data_source.month_week_growth.week
        }
      }))
    })
    getHeadPlan().then((res) => {
      setHeadNum((value) => ({
        ...value,
        规划订单总量: {
          value: res.count.total,
          monthValue: res.count.month_week_growth.month,
          weekValue: res.count.month_week_growth.week
        },
        规划完成度: {
          value: res.finished_rate.total * 100,
          monthValue: res.finished_rate.month_week_growth.month * 100,
          weekValue: res.finished_rate.month_week_growth.week * 100
        }
      }))
    })
    getHeadDemand().then((res) => {
      setHeadNum((value) => ({
        ...value,
        交付需求: {
          value: res.count.total,
          monthValue: res.count.month_week_growth.month,
          weekValue: res.count.month_week_growth.week
        },
        交付数据总量: {
          value: res.delivery_data_count.total,
          monthValue: res.delivery_data_count.month_week_growth.month,
          weekValue: res.delivery_data_count.month_week_growth.week
        }
      }))
    })
    getHeadProject().then((res) => {
      setHeadNum((value) => ({
        ...value,
        服务项目数: {
          value: res.total,
          monthValue: res.month_week_growth.month,
          weekValue: res.month_week_growth.week
        }
      }))
    })
  }, [])

  return (
    <div className="count-line">
      {countItems.map((it) => (
        <div className="count-item" key={it.label}>
          <img src={it.img} alt={it.label} />
          <div className="count-info">
            <div className="count-title">{it.unit ? `${it.label}/${it.unit}` : it.label}</div>
            <div className="count-num">
              <CountUp end={headNum[it.label].value} separator="," decimals={it.percent ? 2 : 0} suffix={it.percent ? '%' : ''} />
            </div>
            <div className="count-change">
              <TrendNum label="本月" value={headNum[it.label].monthValue} decimals={it.percent ? 2 : 0} suffix={it.percent ? '%' : ''} />
            </div>
            <div className="count-change">
              <TrendNum label="本周" value={headNum[it.label].weekValue} decimals={it.percent ? 2 : 0} suffix={it.percent ? '%' : ''} />
            </div>
          </div>
        </div>
      ))}
    </div>
  )
}

const tableStatus = [
  {
    label: '可用',
    key: 2,
    color: '#1FCAC9'
  },
  {
    label: '规划中',
    key: 1,
    color: '#F2A139'
  },
  {
    label: '废弃',
    key: -1,
    color: '#87A7BF'
  }
]

const sourceStatus = [
  {
    label: '可用',
    key: 2,
    color: '#1FCAC9'
  },
  {
    label: '规划中',
    key: 1,
    color: '#F2A139'
  },
  {
    label: '停止更新',
    key: 3,
    color: '#fff538'
  },
  {
    label: '废弃',
    key: -1,
    color: '#87A7BF'
  }
]

interface CardPieData {
  name: string
  data: Array<{
    name: string
    value: number
  }>
  unit: string
  title: { text: string | number; subtext: string }
  monthValue: number
  weekValue: number
}

const CardAssets = () => {
  const navigate = useNavigate()
  const [tablePieData, setTablePieData] = useState<CardPieData>({
    name: '数据表',
    data: [],
    title: {
      text: '0',
      subtext: '总量/张'
    },
    unit: '张',
    monthValue: 0,
    weekValue: 0
  })

  const [sourcePieData, setSourcePieData] = useState<CardPieData>({
    name: '数据源',
    data: [],
    title: {
      text: '0',
      subtext: '总量/个'
    },
    unit: '个',
    monthValue: 0,
    weekValue: 0
  })
  const [tagInfos, setTagInfos] = useState<
    Array<{
      label: string
      key: 'tag_tree' | 'tag' | 'online_rule'
      value: number
      monthTrend: number
      weekTrend: number
    }>
  >([
    {
      label: '标签树/个',
      key: 'tag_tree',
      value: 0,
      monthTrend: 0,
      weekTrend: 0
    },
    {
      label: '标签/个',
      key: 'tag',
      value: 0,
      monthTrend: 0,
      weekTrend: 0
    },
    {
      label: '上线规则/个',
      key: 'online_rule',
      value: 0,
      monthTrend: 0,
      weekTrend: 0
    }
  ])

  useEffect(() => {
    getCardTable().then((res) => {
      setTablePieData({
        name: '数据表',
        data: tableStatus.map((state) => ({
          name: state.label,
          value: res.status_agg.find((item) => item.status === state.key)?.count ?? 0
        })),
        title: {
          text: res.total,
          subtext: '总量/张'
        },
        unit: '张',
        monthValue: res.month_week_growth.month,
        weekValue: res.month_week_growth.week
      })
    })
    getCardSource().then((res) => {
      setSourcePieData({
        name: '数据源',
        data: sourceStatus.map((state) => ({
          name: state.label,
          value: res.status_agg.find((item) => item.status === state.key)?.count ?? 0
        })),
        unit: '个',
        title: {
          text: res.total,
          subtext: '总量/个'
        },
        monthValue: res.month_week_growth.month,
        weekValue: res.month_week_growth.week
      })
    })
    getCardTag().then((res) => {
      setTagInfos((value) =>
        value.map((item) => ({
          ...item,
          value: res[item.key].total,
          monthTrend: res[item.key].month,
          weekTrend: res[item.key].week
        }))
      )
    })
  }, [])

  return (
    <div
      onClick={() => {
        navigate(`/home/DataProperty`)
      }}>
      <div className="card-title">数据资产</div>
      <div className="sub-title">资产统计</div>
      <div className="sub-separate-content h-264px">
        <PieChart pieData={tablePieData} colors={tableStatus.map((it) => it.color)}>
          <>
            <span className="absolute top-14px left-14px chart-name">{tablePieData.name}</span>
            <span className="absolute bottom-35px left-20px chart-name flex gap-14px">
              <TrendNum label="本月" value={tablePieData.monthValue} />
              <TrendNum label="本周" value={tablePieData.weekValue} />
            </span>
          </>
        </PieChart>
        <PieChart pieData={sourcePieData} colors={sourceStatus.map((it) => it.color)}>
          <>
            <span className="absolute top-14px left-14px chart-name">{sourcePieData.name}</span>
            <span className="absolute bottom-35px left-20px chart-name flex gap-14px">
              <TrendNum label="本月" value={sourcePieData.monthValue} />
              <TrendNum label="本周" value={sourcePieData.weekValue} />
            </span>
          </>
        </PieChart>
      </div>
      <div className="sub-title">标签规则统计</div>
      <div className="sub-separate-content h-96px">
        {tagInfos.map((item) => (
          <div key={item.key} className="tag-info-item">
            <div>
              <span className="info-item-label">{item.label}</span>
              <CountUp className="info-item-value" end={item.value} separator="," />
            </div>
            <div>
              <TrendNum label="本月" value={item.monthTrend} />
              <TrendNum label="本周" value={item.weekTrend} />
            </div>
          </div>
        ))}
      </div>
    </div>
  )
}

const CardDemand = () => {
  const navigate = useNavigate()
  const [demandInfos, setDemandInfos] = useState<
    Array<{
      label: string
      key: 'count' | 'answer_rate' | 'finish_rate' | 'positive_review_rate'
      value: number
      percent: boolean
      monthValue: number
      weekValue: number
    }>
  >([
    {
      label: '需求订单',
      key: 'count',
      value: 0,
      percent: false,
      monthValue: 0,
      weekValue: 0
    },
    {
      label: '响应率',
      key: 'answer_rate',
      value: 0,
      percent: true,
      monthValue: 0,
      weekValue: 0
    },
    {
      label: '完成率',
      key: 'finish_rate',
      value: 0,
      percent: true,
      monthValue: 0,
      weekValue: 0
    },
    {
      label: '好评率',
      key: 'positive_review_rate',
      value: 0,
      percent: true,
      monthValue: 0,
      weekValue: 0
    }
  ])
  const [topRank, setTopRank] = useState<
    Array<{
      table_name: string
      delivered_count: number
    }>
  >([])

  useEffect(() => {
    getCardDemand().then((res) => {
      setDemandInfos((value) =>
        value.map((item) => ({
          ...item,
          value: res[item.key].total * (item.percent ? 100 : 1),
          monthValue: res[item.key].month_week_growth.month * (item.percent ? 100 : 1),
          weekValue: res[item.key].month_week_growth.week * (item.percent ? 100 : 1)
        }))
      )
    })
    getCardTopRank().then((res) => {
      setTopRank(res)
    })
  }, [])

  return (
    <div
      onClick={() => {
        navigate(`/home/DataOperate`)
      }}>
      <div className="card-title">数据运营</div>
      <div className="sub-title">需求总览</div>
      <div className="sub-separate-content">
        {demandInfos.map((it) => (
          <div key={it.key} className="flex flex-col items-center gap-8px py-18px">
            <CountUp className="info-item-value" end={it.value} separator="," decimals={it.percent ? 2 : 0} suffix={it.percent ? '%' : ''} />
            <span className="info-item-label pb-7px">{it.label}</span>
            <TrendNum label="本月" value={it.monthValue} decimals={it.percent ? 2 : 0} suffix={it.percent ? '%' : ''} />
            <TrendNum label="本周" value={it.weekValue} decimals={it.percent ? 2 : 0} suffix={it.percent ? '%' : ''} />
          </div>
        ))}
      </div>
      <div className="sub-title">热门资源Top5</div>
      <table>
        <thead>
          <tr>
            <th>排名</th>
            <th>数据表</th>
            <th>交付需求/个</th>
          </tr>
        </thead>
        <tbody>
          {topRank.map((item, index) => (
            <tr key={item.table_name}>
              <td>{index + 1}</td>
              <td>{item.table_name}</td>
              <td>{item.delivered_count}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  )
}

const monitorItems = [
  {
    label: '在建',
    key: 'building_total'
  },
  {
    label: '月新增',
    key: 'month_received'
  },
  {
    label: '月完成',
    key: 'month_finished'
  },
  {
    label: '周新增',
    key: 'week_received'
  },
  {
    label: '周完成',
    key: 'week_finished'
  }
] as const

const trendUrl = {
  plan: {
    label: '规划订单',
    url: getCardPlanTrend
  },
  production: {
    label: '生产订单',
    url: getCardProductionTrend
  }
}

enum lineName {
  finished = '完成',
  received = '新增'
}

const CardProduction = () => {
  // const navigate = useNavigate()

  const [planOrder, setPlanOrder] = useState(
    monitorItems.map((it) => ({
      ...it,
      value: 0
    }))
  )
  const [productionOrder, setProductionOrder] = useState(
    monitorItems.map((it) => ({
      ...it,
      value: 0
    }))
  )
  const [activeChart, setActiveChart] = useState<keyof typeof trendUrl>('plan')

  const [lineData, setLineData] = useState<
    Array<{
      name: string
      data: Array<{
        name: string
        value: number
      }>
    }>
  >([])

  useEffect(() => {
    getCardPlan().then((res) => {
      setPlanOrder((value) =>
        value.map((item) => ({
          ...item,
          value: res[item.key]
        }))
      )
    })
    getCardProduction().then((res) => {
      setProductionOrder((value) =>
        value.map((item) => ({
          ...item,
          value: res[item.key]
        }))
      )
    })
  }, [])

  useEffect(() => {
    const nowTime = dayjs()
    trendUrl[activeChart]
      .url({
        month_min: nowTime.subtract(5, 'month').format('YYYY-MM'),
        month_max: nowTime.format('YYYY-MM')
      })
      .then((res) => {
        let allMonth = [...res.received.map((item) => item.month), ...res.finished.map((item) => item.month)]
        allMonth = [...new Set(allMonth)]
        allMonth.sort()

        const received = {
          name: lineName['received'],
          data: allMonth.map((name) => ({
            name,
            value: res.received.find((it) => it.month === name)?.count ?? 0
          }))
        }

        const finished = {
          name: lineName['finished'],
          data: allMonth.map((name) => ({
            name,
            value: res.finished.find((it) => it.month === name)?.count ?? 0
          }))
        }

        setLineData([received, finished])
      })
  }, [activeChart])
  const getActiveChart = (e: any, key: any) => {
    e.stopPropagation() //阻止事件冒泡
    setActiveChart(key)
  }
  return (
    <div
    // onClick={() => {
    //   navigate(`/home/DataProduce`)
    // }}>
    >
      <div className="card-title">数据生产</div>
      <div className="sub-title">生产监控</div>
      <div className="sub-separate-content">
        <div className="flex flex-col gap-8px p-20px">
          <div className="flex gap-4px pb-6px items-center">
            <span className="info-item-label ">规划订单（在建）</span>
            <CountUp className="info-item-value" end={planOrder[0].value} separator="," />
          </div>
          <div className="grid grid-cols-2 gap-10px">
            {planOrder.slice(1).map((it) => (
              <div key={it.key} className="normal-add-text">
                <span>{it.label}</span>
                <span>{it.value}</span>
              </div>
            ))}
          </div>
        </div>
        <div className="flex flex-col gap-8px p-20px">
          <div className="flex gap-4px pb-6px items-center">
            <span className="info-item-label ">生产订单（在建）</span>
            <CountUp className="info-item-value" end={productionOrder[0].value} separator="," />
          </div>
          <div className="grid grid-cols-2 gap-10px">
            {productionOrder.slice(1).map((it) => (
              <div key={it.key} className="normal-add-text">
                <span>{it.label}</span>
                <span>{it.value}</span>
              </div>
            ))}
          </div>
        </div>
      </div>
      <div className="sub-title">
        月度订单完成趋势
        <div className="switch-tab">
          {(Object.keys(trendUrl) as Array<keyof typeof trendUrl>).map((key) => (
            <span key={key} className={activeChart === key ? 'active' : ''} onClick={(e: any) => getActiveChart(e, key)}>
              {trendUrl[key].label}
            </span>
          ))}
        </div>
      </div>
      <div className="h-238px">
        <LineChart lineData={lineData}></LineChart>
      </div>
    </div>
  )
}

const processItems: Array<{
  label: string
  img?: string
}> = [
  {
    label: '数据资产',
    img: step1
  },
  {
    label: '数据运营'
  },
  {
    label: '数据需求',
    img: step2
  },
  {
    label: '投入生产'
  },
  {
    label: '数据规划',
    img: step3
  },
  {
    label: ''
  },
  {
    label: '实施生产',
    img: step4
  }
]

const BottomItemNames = [
  ['using_total', '总数'],
  ['month_received', '月新增'],
  ['month_finished', '月完成'],
  ['week_received', '周新增'],
  ['week_finished', '周完成']
] as const

const BottomItems = () => {
  const [assets, setAssets] = useState({
    value: 0,
    monthValue: 0,
    weekValue: 0
  })
  const [demand, setDemand] = useState({
    using_total: 0,
    month_received: 0,
    week_received: 0,
    month_finished: 0,
    week_finished: 0
  })
  const [plan, setPlan] = useState({
    using_total: 0,
    month_received: 0,
    week_received: 0,
    month_finished: 0,
    week_finished: 0
  })
  const [production, setProduction] = useState({
    using_total: 0,
    month_received: 0,
    week_received: 0,
    month_finished: 0,
    week_finished: 0
  })

  const getTypeData = (key: string) => {
    let data = {
      using_total: 0,
      month_received: 0,
      week_received: 0,
      month_finished: 0,
      week_finished: 0
    }
    switch (key) {
      case '数据需求':
        data = demand
        break
      case '数据规划':
        data = plan
        break
      case '实施生产':
        data = production
        break
    }
    return data
  }

  useEffect(() => {
    getBottomAssets().then((res) => {
      setAssets({
        value: res.total,
        monthValue: res.month_week_growth.month,
        weekValue: res.month_week_growth.week
      })
    })
    getBottomDemand().then((res) => {
      setDemand(res)
    })
    getBottomPlan().then((res) => {
      setPlan(res)
    })
    getBottomProduction().then((res) => {
      setProduction(res)
    })
  }, [])

  return (
    <div className="item-line">
      {processItems.map((it, index) => (
        <div key={it.label}>
          {it.img ? <img src={it.img} alt={it.label} /> : <img src={shortLine} alt="line" />}
          {it.img ? (
            index === 0 ? (
              <div>
                <div>
                  <span>{it.label}</span>
                  <CountUp end={assets.value} separator="," />
                </div>
                <div>
                  {' '}
                  <div className="normal-add-text">
                    <span>月新增</span>
                    <span>{assets.monthValue}</span>
                  </div>
                  <div className="normal-add-text">
                    <span>周新增</span>
                    <span>{assets.weekValue}</span>
                  </div>
                </div>
              </div>
            ) : (
              <div>
                <div>
                  <span>{it.label}</span>
                  <CountUp end={getTypeData(it.label)[BottomItemNames[0][0]]} separator="," />
                </div>
                <div>
                  {BottomItemNames.slice(1).map((item) => (
                    <div key={item[0]} className="normal-add-text">
                      <span>{item[1]}</span>
                      <span>{getTypeData(it.label)[item[0]]}</span>
                    </div>
                  ))}
                </div>
              </div>
            )
          ) : (
            <span>{it.label}</span>
          )}
        </div>
      ))}
    </div>
  )
}

const Home = () => {
  return (
    <>
      <div className="board-home-layout">
        <HomeHead />
        <div className="card-line">
          <CardAssets />
          <CardDemand />
          <CardProduction />
        </div>
        <div className="process-line">
          <BottomItems />
          <div className="bottom-line">
            <img src={longLine} alt="line" />
            <div>资产上架</div>
          </div>
        </div>
      </div>
    </>
  )
}

export default Home
